<template>
  <div>
    <SearchBar :keyword="condition" :placeholder="placeholder" :viewoptionArr="viewoptionArr" @handleClickViewOption="handleClickViewOption"
      @hanldeClickFilter="hanldeClickFilter" @handleClickSearch="handleClickSearch"
      @handleInputSearch="handleInputSearch"></SearchBar>

    <van-popup v-model:show="isShowFilter" position="right" :style="{ height: '100%', width: '90%' }">
      <Filter @back="hanldeClickFilter" @handleClickFilterFind="handleClickFilterFind" :object="route.query.idobject"></Filter>
    </van-popup>

    <van-popup v-model:show="isShowViewOptions" position="top" :style="{ height: 'auto', width: '100%' }">
      <van-row class="L-viewoption-row" :class="viewoption === item[0] ? 'on' : ''" @click="viewoption = item[0]"
        type="flex" align="center" justify="space-between" v-for="(item, index) in viewoptionArr" :key="index">
        <van-col>{{ item[1] }}</van-col>
        <van-col> <van-icon name="success" v-if="viewoption === item[0]" /></van-col>
      </van-row>
    </van-popup>

    <van-list v-model:loading="isLoading" :finished="finished" finished-text="没有更多了" @load="onLoad">
      <JhglItem v-for="(item, index) in list" :key="index" idobject="jhgl" :item="item"></JhglItem>
    </van-list>

    <van-floating-bubble icon="plus" axis="xy" magnetic="x" v-model:offset="offset"
      @click="showScenarioPopover = true" />

    <van-action-sheet cancel-text="取消" v-model:show="showScenarioPopover" :actions="scenarioArr"
      @select="handleClickAdd" />

  </div>

</template>

<script setup lang="ts">
import { useRouter, useRoute } from "vue-router";
const router = useRouter();
const route = useRoute();

import {
  onMounted,
  ref,
  defineProps,
  watch,
  onActivated,
  defineExpose,
} from "vue";

import { apiConfigurable } from "@/request/api/api";
import { closeToast, showLoadingToast } from "vant";
import SearchBar from "@/components/common/SearchBar.vue";
import Filter from "@/components/common/Filter.vue";
import JhglItem from "@/components/base/Jhgl/JhglItem.vue";

import { useCheck } from "@/hooks/hooks.js";
const { checkCustomized } = useCheck();

import { useRouterStore } from "@/stores/router";
const routerStore = useRouterStore();

const offset = ref({ x: -20, y: 440 });



const list = ref([]);
const startline = ref(1);
const pagecount = ref(10); //每页条数
const firstLoad = ref(true); //是否第一次加载
const isLoading = ref(false); //是否加载中
const finished = ref(false); //列表是否加载完成

const sortType = ref(""); //排序方式
const sortBy = ref(""); //排序字段

const extract = ref("");
const searchedtags = ref([]);

const viewoptionArr = ref([]); //视图选项数组
const viewoption = ref(""); //当前视图

const condition = ref(""); //搜索关键字
const placeholder = ref("")

function handleClickSearch(value: string) {
  condition.value = value;
  initCondition();
  onLoad();
}

function handleInputSearch(value: string) {
  condition.value = value;
}

//初始化查询条件
function initCondition() {
  startline.value = 1;
  finished.value = false;
  list.value = [];

  conditiondata.value = [];
  sortBy.value = "";
  sortType.value = "asc";
  searchedtags.value = [];

  viewoption.value = "";
}

//显示视图条件
const isShowViewOptions = ref(false);
function handleClickViewOption(value: boolean) {
  isShowViewOptions.value = value;
}

//显示过滤层
const isShowFilter = ref(false);
const conditiondata = ref([]);
function hanldeClickFilter(value: boolean) {
  isShowFilter.value = value;
}

function handleClickFilterFind(filterObj) {
  initCondition();
  conditiondata.value = filterObj.fieldArr;
  sortBy.value = filterObj.sortBy;
  sortType.value = filterObj.sortType;
  searchedtags.value = filterObj.selectedTags;
  isShowFilter.value = false;
  onLoad();
}

interface tags {
  [id: string]: boolean;
}
interface data {
  [key: string]: any;
}

function onLoad() {
  const { idobject, idtemplate, stitle } = route.query;
  const tags: tags = {};
  searchedtags.value.forEach((item) => {
    tags[item] = true;
  });

  let data: data = {
    startline: startline.value,
    pagecount: pagecount.value,
    condition: condition.value,
    orderby: sortBy.value,
    ascdesc: sortType.value,
    viewoption: viewoption.value,
    extract: extract.value,
    tags: JSON.stringify(tags),
  };

  for (let i = 0; i < conditiondata.value.length; i++) {
    data[i + "_viewcondition_field"] = conditiondata.value[i].viewcondition_field;
    data[i + "_viewcondition_relfield"] = conditiondata.value[i].viewcondition_relfield;
    data[i + "_viewcondition_value"] = conditiondata.value[i].viewcondition_value;
    data[i + "_viewcondition_comparison"] = conditiondata.value[i].viewcondition_comparison;
    data[i + "_viewcondition_object"] = conditiondata.value[i].viewcondition_object;
    data[i + "_viewcondition_uitype"] = conditiondata.value[i].viewcondition_uitype;
  }

  showLoadingToast({
    message: "加载中...",
    forbidClick: true,
    duration: 0,
  });

  isLoading.value = true;

  const loadapi = `${idobject as string}.list.do`;

  apiConfigurable(loadapi, data).then((res) => {
    if (res.data?.jsondata?.fieldValue.length < pagecount.value) {
      finished.value = true;
    }
    list.value = [...list.value, ...res.data?.jsondata?.fieldValue];
    startline.value = list.value.length + 1;

    

    if (firstLoad.value) {
      viewoptionArr.value = res.data?.viewOptions || [];
      viewoption.value = viewoptionArr.value[0][0];
      firstLoad.value = false;
    }

    if(res.data?.viewcondition?.length>0){
      placeholder.value = res.data?.viewcondition.reduce((pre,item,index)=>{
        return `${pre}${index===0 ? '' : '/'}${item.viewcondition_title}`
      },"请输入")
    }
    closeToast();
    isLoading.value = false;
  });
}

interface scenarioItemType {
  name: string;
  id: number;
  selectobj: string;
  accountobj: string;
}

function handleClickAdd(scenarioItem: scenarioItemType) {
  const { idobject, idtemplate, stitle } = route.query;
  const path = `/${idobject}Form`


  const { name, id, selectobj, accountobj } = scenarioItem;

  const query = {
    idobject,
    idtemplate,
    stitle,
    scenarioId: id,
    scenarioTitle: name,
    scenarioSelectobj: selectobj,
    scenarioAccountobj: accountobj,
  };
  showScenarioPopover.value = false

  router.push({
    path,
    query,
  });
}

const scenarioArr = ref<scenarioItemType[]>([]);
const showScenarioPopover = ref(false);
function getScenario() {
  apiConfigurable("scenario.getlist.do").then((res) => {
    if (res.code === 0) {
      const scenarios = Object.entries(res.data.scenarios) as [];
      const scenarioInfos = res.data.scenarioInfos

      scenarioArr.value = scenarios.map((item, index) => {

        return { name: item[1], id: item[0], selectobj: scenarioInfos[item[0]].selectobj, accountobj: scenarioInfos[item[0]].accountobj };
      });
    }
  });
}

onMounted(() => {
  getScenario();
});

onActivated(() => {
  if (routerStore.mode === "reload") {
    initCondition();
    onLoad();
    getScenario();

    routerStore.mode = "";
  }
});
</script>

<style scoped></style>